package com.hljx.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hljx.config.exception.DataException;
import com.hljx.dto.*;
import com.hljx.entity.SysBind;
import com.hljx.entity.SysDictItem;
import com.hljx.excel.ExcelTransfer;
import com.hljx.mapper.sys.SysBindMapper;
import com.hljx.service.SysAccountingUnitService;
import com.hljx.service.SysBindService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hljx.vo.AccountingUnitDataVO;
import com.hljx.vo.HospitalDataVO;
import com.hljx.vo.SysDictVO;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.TreeSet;
import java.util.stream.Collectors;

/**
 * <p>
 * 科室对照表 服务实现类
 * </p>
 *
 * @author gx
 * @since 2023-09-21
 */
@Service
public class SysBindServiceImpl extends ServiceImpl<SysBindMapper, SysBind> implements SysBindService {

    @Autowired
    SysAccountingUnitService accountingUnitService;

    @Autowired
    private ExcelTransfer<SysBind> bindExcelTransfer;

    @Override
    public List<HospitalDataVO> listHospitalDataByPage(HospitalDataDTO dto) {
        return baseMapper.listHospitalDataByPage(dto);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateSysBind(SysBindDTO dto) {
        List<SysBind> list = new ArrayList<>();
        dto.getHospitalDataVOList().forEach(s->{
            SysBind sysBind = new SysBind();
            BeanUtil.copyProperties(dto,sysBind);
            BeanUtil.copyProperties(s,sysBind);
            list.add(sysBind);
        });
        return saveOrUpdateBatch(list);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean batchComparison() {
        //查询需要对照的科室
        HospitalDataDTO hospitalDataDTO = new HospitalDataDTO();
        List<HospitalDataVO> hospitalDataVOS = baseMapper.listHospitalDataByPage(hospitalDataDTO);
        AccountingDataPageDTO accountingDataPageDTO = new AccountingDataPageDTO();
        List<AccountingUnitDataVO> page = accountingUnitService.listAccountingDataByPage(accountingDataPageDTO);
        //根据科室名称去重
        List<AccountingUnitDataVO> result = page.stream().collect(Collectors.collectingAndThen(
                Collectors.toCollection(()->new TreeSet<>(Comparator.comparing(AccountingUnitDataVO::getSysDeptName))),ArrayList::new
        ));
        List<SysBind> sysBinds = new ArrayList<>();
        for (HospitalDataVO s : hospitalDataVOS) {
            for (AccountingUnitDataVO u : result) {
                if(s.getHospitalDeptName().equals(u.getSysDeptName())){
                    SysBind sysBind = new SysBind();
                    BeanUtil.copyProperties(u,sysBind);
                    BeanUtil.copyProperties(s,sysBind);
                    sysBinds.add(sysBind);
                }
            }
        }
        return saveOrUpdateBatch(sysBinds);
    }

    @Override
    public IPage<SysBind> listSysBindByPage(SysBindPageDTO dto) {
        Page<SysBind> page = new Page<>(dto.getPageNum(),dto.getPageSize());
        QueryWrapper<SysBind> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(SysBind::getDeleteFlag,0).isNotNull(SysBind::getSysDeptCode);
        if(StringUtils.isNotBlank(dto.getName())){
            queryWrapper.lambda().and(i->i.like(SysBind::getHospitalDeptName,dto.getName())
                    .or().like(SysBind::getSysDeptName,dto.getName()));
        }
        return baseMapper.listSysBindByPage(page,queryWrapper);
    }

    @Override
    public Boolean revokeSysBind(Long id) {
        return removeById(id);
    }

    @Override
    public void importIw(MultipartFile file, HttpServletResponse response) throws ClassNotFoundException {
        List<SysBind> list = list(Wrappers.lambdaQuery(SysBind.class));
        bindExcelTransfer.importExcel(file, this, lists -> {
            ArrayList<SysBind> arrayList = new ArrayList<>();
            lists.forEach(e -> {
                if (list.stream().noneMatch(l -> e.getHospitalDeptName().equals(l.getHospitalDeptName())) || list.stream().noneMatch(l -> e.getHospitalDeptCode().equals(l.getHospitalDeptCode())) ) {
                    arrayList.add(e);
                }
            });
            return arrayList;
        });
    }

    @Override
    public void export(ExportBindDTO dto, HttpServletResponse response) throws ClassNotFoundException {
        List<SysBind> list = new ArrayList<>();
        if (dto.getType() == null) {
            throw new DataException("入参数据为空",201);
        }
        if (dto.getType() == 1) {
            list= baseMapper.selectList(new LambdaQueryWrapper<SysBind>().in(SysBind::getId, dto.getIds()));
        }
        bindExcelTransfer.exportExcel(response, list, "数据对照", "sheet1", SysBind.class);

    }
}
